package artaza.clasesdao;
import java.io.Serializable;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import org.springframework.transaction.annotation.Transactional;

public class GenericDAOJPAImpl<T, PK extends Serializable> implements GenericDAO<T, PK> {

    @PersistenceContext
    EntityManager em;

    @Transactional
    @Override
    public void insert(T t) {
        em.persist(t);
    }

    @Override
    public T findByPK(Class<T> typeClass, PK id) {
        return em.find(typeClass, id);
    }

    @SuppressWarnings("unchecked")
    @Override
    public List<T> getAll(Class<T> typeClass) {

        final StringBuilder sql = new StringBuilder("select c from ").append(
                typeClass.getSimpleName()).append(" c");
        return (List<T>) em.createQuery(sql.toString()).getResultList();

    }

    @Transactional
    @Override
    public void remove(T object) {

        em.remove(em.merge(object));
    }

    @Transactional
    @Override
    public GenericDAO<T, PK> update(T object) {
        em.merge(object);
        return this;
    }


    @Transactional
    @Override
    public int removeAll(Class<T> typeClass) {
        String sql = "DELETE FROM " + typeClass.getSimpleName() + " c";
        return em.createQuery(sql).executeUpdate();
    }

    
    @Override
    public Integer countAll(Class<T> typeClass) {
        final StringBuilder sql = new StringBuilder("select count(c) from ").append(
                typeClass.getSimpleName()).append(" c");
        return (Integer) em.createQuery(sql.toString()).getSingleResult();
    }

}
